const app = getApp();

Page({
  data: {
    currentIndex: 0,
    banners: [
      { id: 1, src: "/static/index/banner1.png" },
      { id: 2, src: "/static/index/banner1.png" },
      { id: 3, src: "/static/index/banner3.png" },
      { id: 4, src: "/static/index/banner4.png" },
    ],
    addressName: '',
    latitude: '',
    longitude: '',
  },

  onLoad() {
    // 读取缓存中的位置信息
    const latitude = wx.getStorageSync('latitude') || '';
    const longitude = wx.getStorageSync('longitude') || '';
    const addressName = wx.getStorageSync('addressName') || '';

    this.setData({ latitude, longitude, addressName });

    this.getUserLocation();
  },

  // 获取用户位置
  getUserLocation() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        const { latitude, longitude } = res;

        // 读取缓存中的旧经纬度
        const oldLatitude = this.data.latitude;
        const oldLongitude = this.data.longitude;

        // 只有经纬度变更时才更新数据并获取地址
        if (oldLatitude !== latitude || oldLongitude !== longitude || !this.data.addressName) {
          this.setData({ latitude, longitude }, async () => {
            wx.setStorageSync('latitude', latitude);
            wx.setStorageSync('longitude', longitude);
            await this.getAddressFromLocation(latitude, longitude);
          });
        }
      },
      fail: (err) => {
        console.error('获取位置失败:', err);
        if (err.errMsg.includes('auth')) {
          wx.showModal({
            title: '定位权限未开启',
            content: '请在设置中允许小程序获取位置信息。',
            confirmText: '去设置',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting();
              }
            }
          });
        } else {
          wx.showToast({
            title: '无法获取位置，请检查网络',
            icon: 'none',
          });
        }
      }
    });
  },

  // 获取地址信息
  async getAddressFromLocation(latitude, longitude) {
    const key = 'D2PBZ-ZTOWB-ZNHUM-NNGLM-5WYKT-JGBCG'; // 腾讯地图 API Key
    const getAddressUrl = `https://apis.map.qq.com/ws/geocoder/v1?location=${latitude},${longitude}&key=${key}`;

    console.log('请求地址:', getAddressUrl);

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getAddressUrl,
          success: resolve,
          fail: reject,
        });
      });

      if (res.data && res.data.status === 0) {
        const address = res.data.result.address;
        console.log('解析地址成功:', address);

        this.setData({ addressName: address });
        wx.setStorageSync('addressName', address);
      } else {
        console.error('地址解析失败:', res.data.message || '未知错误');
        wx.showToast({ title: '地址解析失败，请稍后重试', icon: 'none' });
      }
    } catch (err) {
      console.error('请求失败:', err);
      wx.showToast({ title: '网络异常，请检查网络', icon: 'none' });
    }
  },

  // 拨打电话
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: '18361310400',
      fail: (err) => {
        console.log("用户取消了拨打电话", err);
      }
    });
  }
});
